<template>
  <div>
    <div class="org-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>用户与权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="org-container">
      <div class="org-content">
        <div class="org-header">
          <span>系统用户管理</span>
          <el-button type="primary" plain @click="inviteUser()">邀请人员</el-button>
        </div>
        <div class="user-operator">
          <div>
            <span class="org-label">邀请时间</span>
            <el-date-picker
              class="user-dateRange"
              size="mini"
              v-model="dateValue"
              type="daterange"
              align="right"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
          <div>
            <span class="org-label">组织机构</span>
            <el-cascader
              size="mini"
              class="user-cascader"
              :options="organizationList"
              v-model="selectedOrgForDetail"
              :props="organizationListProps"
              change-on-select
              clearable
            ></el-cascader>
          </div>
          <div class="org-position">
            <span class="org-label">账号状态</span>
            <el-select v-model="isAble" size="mini" class="user-isAble" placeholder="全部状态">
              <el-option
                label="全部状态"
                value="">
              </el-option>
              <el-option
                label="可用"
                value="0">
              </el-option>
              <el-option
                label="禁用"
                value="1">
              </el-option>
            </el-select>
          </div>
          <div class="org-filter">
            <el-input
              size="mini"
              v-model="filterStr"
              class="user-filter"
              placeholder="用户名/姓名/员工号/手机号/邮箱"
            >
            </el-input>
          </div>
          <div>
            <el-button size="mini" type="primary" @click="currentPage = 1;onSearch()">搜索</el-button>
          </div>
          <div class="org-label org-right">共{{total}}条数据</div>
        </div>
        <div>
          <el-table
            :data="tableData"
            style="width: 100%">
            <el-table-column
              prop="userName"
              label="用户名">
            </el-table-column>
            <el-table-column
              prop="name"
              label="姓名">
            </el-table-column>
            <el-table-column
              prop="empId"
              label="员工编号">
            </el-table-column>
            <el-table-column
              prop="postName"
              label="岗位">
            </el-table-column>
            <el-table-column
              prop="organizationId"
              label="所属机构">
              <template slot-scope="scope">
                <span>{{ getOrgnizationStr(scope.row.organizationId) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="permIds"
              label="权限">
              <template slot-scope="scope">
                <span>{{ getPermissionStr(scope.row.permIdArr) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="registerTime"
              label="邀请时间">
            </el-table-column>
            <el-table-column
              prop="isAble"
              label="账号状态">
              <template slot-scope="scope">
                <span>{{ scope.row.isAble === 0 ? '启用': '禁用' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="toggleEnable(scope.row)">{{getEnableText(scope.row.isAble)}}</el-button>
                <el-button type="text" @click="editUser(scope.row)">查看/编辑</el-button>
                <el-button type="text" @click="deleteConfirm(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="float: right"
            layout="prev, pager, next"
            :total="total"
            :current-page="currentPage"
            @current-change="pageChange">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      title="编辑权限"
      :visible.sync="editPermissionPanelVisible"
      :close-on-click-modal="false"
      width="80%">
      <p>
        <span>登录账号</span>
        <span>{{ editPermissionForm.phone }}</span>
      </p>
      <p>
        <span>人员信息</span>
        <span>{{ editPermissionForm.name + ' ' + editPermissionForm.userName + ' ' + editPermissionForm.empId+ ' ' + getOrgnizationStr(editPermissionForm.organizationId)+ ' ' + editPermissionForm.postName  }}</span>
      </p>
      <div>
        <span>账号状态</span>
        <el-radio-group v-model="editPermissionForm.isAble" >
          <el-radio :label="0">启用</el-radio>
          <el-radio :label="1">禁用</el-radio>
        </el-radio-group>
      </div>
      <div class="permission-config-container">
        <div class="permission-config-table">
          <div class="user-filter">
            <el-input v-model="filterPermissionStr" size="small" clearable placeholder="权限名称/权限编号"></el-input>
          </div>
          <el-table
            :data="filteredList"
            ref="multipleTable"
            border
            @select="handleSelect"
            @select-all="handleSelectAll"
            height="500">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="id"
              label="权限编号">
            </el-table-column>
            <el-table-column
              prop="permName"
              label="权限名称">
            </el-table-column>
          </el-table>
        </div>
        <div class="permission-config-list">
          <div class="permission-tip">
            已选权限{{ selectedPermission.length }}
          </div>
          <el-table
            :data="selectedPermission"
            height="500">
            <el-table-column
              type="index"
              label="序号">
            </el-table-column>
            <el-table-column
              label="功能名称"
              prop="permName"
              width="200">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="deletePermission(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="user-buttons">
        <el-button type="primary" @click="submitUserPermission">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  export default {
    name: "user-management",
    data() {
      return ({
        filterStr: '',
        editPermissionForm: {
          isAble: 0,
          disabled: false,
        },
        isAble: '',
        dateValue: [],
        tableData: [],
        total: 0,
        editPermissionPanelVisible: false,
        currentPage: 1,
        selectedOrgForDetail: [],
        organizationList: [],
        permissionList: [],
        selectedPermission: [],
        filterPermissionStr: '',
        organizationListProps: {
          children: 'children',
          label: 'name',
          value: 'id'
        },
      })
    },
    computed: {
      filteredList: function() {
        return this.permissionList.filter(item => item.id.toString().indexOf(this.filterPermissionStr) > -1 || item.permName.indexOf(this.filterPermissionStr) > -1)
      },
    },
    mounted() {
      this.getOrganizationList()
      this.getPermissionList()
      this.onSearch()
    },
    methods: {
      getOrganizationList() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          "method":"organizationTree",
          "query":{}
        }).then(res => {
          loading.close()
          this.organizationList = res.data.data

        })
      },
      getPermissionList() {
        this.$http.post(this.GLOBAL.host, {
          "method":"Permission_BaseList",
          "query":{}
        }).then(res => {
          this.permissionList = res.data.data
        })
      },
      getPermissionStr(arr = []) {
        if (!arr) {
          return ''
        }
        return arr.map(id => {
          const permission = _.find(this.permissionList, item => item.id == id) || {}
          return permission.permName || ''
        }).join(' ')
      },
      getOrgnizationStr(id) {
        return _.get(_.last(this.getPathByKey(id, 'id', this.organizationList)), 'name', '')
      },
      toggleEnable(data) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        this.$http.post(this.GLOBAL.host, {
            method:"User_UpdateState",
            data: {
              id: data.id,
              isAble: 1 - data.isAble,
            }
          }
        ).then(res => {
          loading.close()
          if (res.data.code == 200) {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.onSearch()
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      getEnableText(enable) {
        if (enable == 0) {
          return '禁用'
        }
        return '启用'
      },
      editUser(data) {
        this.editPermissionPanelVisible = true
        this.editPermissionForm = data
      },
      deleteConfirm(id) {
        this.$confirm('确定删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          this.deleteUser(id)
        }).catch(() => null)
      },
      deleteUser(id) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        this.$http.post(this.GLOBAL.host, {
            method:"User_Delete",
            data: {
              id,
            }
          }
        ).then(res => {
          loading.close()
          if (res.data.code == 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.onSearch()
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      inviteUser() {
        this.$router.push({ path: 'user/invite' })
      },
      submitUserPermission() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
            method:"User_UpdatePermission",
            data: {
              id:this.editPermissionForm.id,
              isAble:this.editPermissionForm.isAble,
              permIdArr:this.selectedPermission.map(item => item.id)
            }
          }
        ).then(res => {
          loading.close()
          if (res.data.code == 200) {
            this.selectedPermission = []
            this.$refs.multipleTable.clearSelection();
            this.editPermissionPanelVisible = false
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.onSearch()
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      cancel() {
        this.selectedPermission = []
        this.$refs.multipleTable.clearSelection();
        this.editPermissionPanelVisible = false
      },
      pageChange(pageNum) {
        this.currentPage = pageNum;
        this.onSearch()
      },
      onSearch(lastQuery) {
        this.lastQuery = lastQuery || {
          pageNo: this.currentPage || 1,
          pageSize: 10,
          startDate: this.dateValue ? this.dateValue[0] : '',
          endDate: this.dateValue ? this.dateValue[1] : '',
          keyword: this.filterStr,
          organizationId: _.last(this.selectedOrgForDetail),
          isAble: this.isAble,
        };
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
            method:"User_GetList",
            query: this.lastQuery,
          }
        ).then(res => {
          loading.close()
          this.tableData = res.data.data.list
          this.total = res.data.data.total
        })
      },
      getPathByKey(value, key, arr) {
        let temppath = [];
        try {
          function getNodePath(node){
            temppath.push(node);
            //找到符合条件的节点，通过throw终止掉递归
            if (node[key] === value) {
              throw ("GOT IT!");
            }
            if (node.children && node.children.length > 0) {
              for (var i = 0; i < node.children.length; i++) {
                getNodePath(node.children[i]);
              }

              //当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
              temppath.pop();
            }
            else {

              //找到叶子节点时，删除路径当中的该叶子节点
              temppath.pop();
            }
          }
          for (let i = 0; i < arr.length; i++) {
            getNodePath(arr[i]);
          }
        } catch (e) {
          return temppath;
        }
      },
      handleSelect(selection, row) {
        if (_.some(this.selectedPermission, item => item.id === row.id)) {
          this.selectedPermission = _.reject(this.selectedPermission, item => item.id === row.id)
        } else {
          this.selectedPermission = _.concat(this.selectedPermission, row)
        }
      },
      handleSelectAll(selection, row) {
        if (selection.length > 0) {
          this.selectedPermission = selection
        } else {
          this.selectedPermission = []
        }
      },
      deletePermission(row) {
        this.selectedPermission = _.reject(this.selectedPermission, item => item.id === row.id)
        this.$refs.multipleTable.toggleRowSelection(row);
      }
    }
  }
</script>

<style lang="less">
  .user-operator {
    display: flex;
    align-items: center;
    > div {
      margin-right: 15px;
    }
    margin-bottom: 10px;
  }
  .user-dateRange {
    width: 220px !important;
  }
  .user-isAble {
    width: 110px;
  }
  .user-cascader {
    width: 110px;
  }
  .user-filter {
    width: 200px;
    margin-bottom: 10px;
  }
  .user-buttons {
    text-align: center;
    margin-top: 20px;
  }
  .user-operator .org-filter {
    flex: 200px 0 0;
  }
</style>
